<?php

namespace App\Http\Controllers\Admin;

use App\Models\Order;
use App\Models\SpecValue;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
	protected $order_status = [];

	public function __construct(){
	 	$this->order_status = [
	 		'0'=>'未支付',
			'1'=>'已支付',
			'2'=>'已发货',
			'3'=>'确认收货',
			'4'=>'已评价',
			'5'=>'申请售后',
			'6'=>'售后中',
			'7'=>'售后完成',
		];
	}
	/**
	 * 订单列表
	 * User: Clannad ~ ☆
	 * DataTime：2019/11/19 0019 10:12
	 */
    public function index()
    {
        $orderList = Order::query()
//				->select(
//					DB::raw('
//						(select GROUP_CONCAT(simple_name) as area from my_region
//							where id in (my_order.province_id,my_order.city_id,my_order.county_id)
//						) as area'),
//					'status','goods_total','price_total','created_at','id','order_sn','user_id'
//				)
				->select(
					DB::raw('
							(select whole_name from my_region
								where id = my_order.county_id
							) as area'),
					'status','goods_total','price_total','created_at','id','order_sn','username','tel'
				)
                ->orderBy('id','desc')
				->paginate(10);

		$order_stats = $this->order_status;

		return view('admin.order.index',compact('orderList','order_stats'));
    }

	/**
	 * 订单详情
	 * User: Clannad ~ ☆
	 * DataTime：2019/11/19 0019 14:43
	 * @param $id
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
    public function detail($id)
    {
    	$order = Order::query()
				->select(
					DB::raw('
							(select whole_name from my_region
								where id = my_order.county_id
							) as area'),
					'status','goods_total','price_total','created_at','id','order_sn','username','tel',
					'pay_time','pay_type','address','username','tel','remark','express_no','user_id'
				)
				->with(['user'=>function($query){
					return $query->select('username','nick_name','id');
				}])
				->findOrFail($id);

    	$order_info = $order->orderInfo()->select('goods_id','goods_name','thumb','sku_list','number','price')->get()->toArray();

    	foreach ($order_info as $k => $v) {
    	    $spec = SpecValue::query()
					->select('spec_name','value')
					->leftJoin('spec','spec.id','=','spec_value.spec_id')
					->whereIn('spec_value.id',explode(',',$v['sku_list']))
					->withTrashed() //包含软删除的记录  //onlyTrashed() 只是软删除的记录
					->get()->toArray();
    	    $order_info[$k]['spec'] = $spec;
    	}

    	$order_status = $this->order_status;

		return view('admin.order.detail',compact('order','order_info','order_status'));
    }

	/**
	 * 删除订单
	 * User: Clannad ~ ☆
	 * DataTime：2019/11/19 0019 14:43
	 * @param $id
	 */
    public function destroy($id)
    {
        //只有未支付的订单才可以删除 订单不做物理删除
        $order = Order::findOrFail($id);
        $order->delete();

        return back()->with('success','删除成功');
    }
}
